/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tubes1sister.tools;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import tubes1sister.metainfo;

/**
 *
 * @author Muhammad Anis
 */
public class FileProcessor {

    public String filename;
    //constructor

    public FileProcessor(String filename, int tipe_process) {
        this.filename = filename;
    }

    public metainfo ProcessMetainfoData() {
        metainfo temp = new metainfo();
        FileInputStream is;
        String data;
        String[] data2;
        try {
            debug.debugObject("NamaFile: " + filename);
            is = new FileInputStream(filename);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            //dapatkan informasi filename, filelength,piece length
            data = br.readLine();
            //split
            data2 = data.split("\\s+");
            if (data2.length < 3) {
                debug.debugObject("Format File Salah");
            }
            //data benar, ambil bagian yang diperlukan
            temp.filename = data2[0];
            System.out.println("data 2 [1] : " + data2[1]);
            temp.filelength = Long.parseLong(data2[1]);
            temp.piecelength = Integer.parseInt(data2[2]);


            data = br.readLine();
            //split
            if (data.length() < 1) {
                debug.debugObject("Format File Salah");
            }
            temp.announce = data;

            data = br.readLine();
            //split
            if (data.length() < 1) {
                debug.debugObject("Format File Salah");
            }
            temp.pieces = data;

        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileProcessor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException e) {
            System.out.println("Format File Input Tidak Benar");
        }
        return temp;
    }

    public String getHashValue() throws IOException{
        FileInputStream is = null;
        String message,temp = null;
        try {
            is = new FileInputStream(filename);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while((message=br.readLine())!=null){
                temp=message;
            }
            return temp;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileProcessor.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(FileProcessor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }
}
